package com.sx.gongzhong.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sx.gongzhong.BaseActivity;
import com.sx.gongzhong.R;
import com.sx.gongzhong.adapter.MultiImageAdapter;
import com.sx.gongzhong.model.MsgEvent;
import com.sx.gongzhong.model.PhotoBean;
import com.sx.gongzhong.net.MyRxBus;
import com.sx.gongzhong.pest.HelpAddPest;
import com.sx.gongzhong.pest.UploadFilePest;
import com.sx.gongzhong.utils.BaseUtil;
import com.sx.gongzhong.utils.ToastUtils;
import com.sx.gongzhong.view.IVoidView;
import com.sx.gongzhong.view.UploadFileView;
import com.sx.gongzhong.widget.CountEditText;
import com.sx.gongzhong.widget.LoadDialog;
import com.sx.gongzhong.widget.SuccessDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class HelpAddActivity extends BaseActivity implements UploadFileView, IVoidView {

    @BindView(R.id.et_Title)
    EditText et_Title;
    @BindView(R.id.et_Content)
    CountEditText et_Content;
    @BindView(R.id.tv_Count)
    TextView tv_Count;
    @BindView(R.id.recyclerView)
    RecyclerView rvImageRV;

    private MultiImageAdapter adapter;
    private List<PhotoBean> selectList = new ArrayList<>();

    private String title,content;

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_help_add);
        setTitleName(R.string.help_each_other_add);
        setTitleRight(R.string.confirm);
        ButterKnife.bind(this);
        initViews();
    }

    private void initViews() {
        rvImageRV.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false));
        adapter = new MultiImageAdapter(this, mAddPicClickListener);
        adapter.setSelectMax(6);
        adapter.setList(selectList);
        rvImageRV.setAdapter(adapter);
        et_Content.setMaxNum(500);
        et_Content.setOnEditTextCountLisener(new CountEditText.OnEditTextCountLisener() {
            @Override
            public void setCount(int currentCount) {
                tv_Count.setText(currentCount+"/500");
            }
        });
        findViewById(R.id.tv_right).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                title = et_Title.getText().toString().trim();
                if (BaseUtil.isEmpty(title)){
                    ToastUtils.showToast(HelpAddActivity.this,"请输入标题");
                    return;
                }
                content = et_Content.getText().toString().trim();
                if (BaseUtil.isEmpty(content)){
                    ToastUtils.showToast(HelpAddActivity.this,"请输入问题");
                    return;
                }
                LoadDialog.show(HelpAddActivity.this,"提交中...");
                if (selectList.size() == 0){
                    commit(null);
                }else {
                    List<File> fileList = new ArrayList<>();
                    for (PhotoBean photoBean : selectList){
                        fileList.add(new File(photoBean.getPath()));
                    }
                    new UploadFilePest(HelpAddActivity.this).uploadFile(HelpAddActivity.this,fileList);
                }

            }
        });
    }

    private void commit( List<String> fileIds) {
        LoadDialog.show(HelpAddActivity.this,"提交中...");
        new HelpAddPest(this).addHelp(title,content,fileIds);
    }


    //点击的添加文件的响应
    private MultiImageAdapter.AddPicClickListener mAddPicClickListener = new MultiImageAdapter.AddPicClickListener() {
        @Override
        public void onAddPicClick() {
            int max = 6 - selectList.size();
            if (max > 0) {
                PictureSelector.create(HelpAddActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.MULTIPLE)
                        .maxSelectNum(max)// 最大图片选择数量 int
                        //.previewImage(true)// 是否可预览图片
                        .enableCrop(true)
                        .withAspectRatio(4, 3)
                        .compress(true)
                        .compressGrade(Luban.CUSTOM_GEAR)
                        .compressMaxKB(200)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            } else {
                ToastUtils.showToast(HelpAddActivity.this, "最多上传6张");
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST://选图片
                    List<LocalMedia> picUrls = PictureSelector.obtainMultipleResult(data);
                    if (!picUrls.isEmpty()) {
                        for (LocalMedia localMedia : picUrls) {
                            String path = localMedia.getCompressPath();
                            String type = path.substring(path.lastIndexOf("."));
                            selectList.add(new PhotoBean(path, type));
                        }
                        if (adapter != null) adapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    }

    @Override
    public void showError(String message) {
        LoadDialog.dismiss(HelpAddActivity.this);
        ToastUtils.showToast(HelpAddActivity.this,message);
    }

    @Override
    public void uploadSuccess(List<PhotoBean> beans) {
        List<String> fileIds = new ArrayList<>();
        for (PhotoBean b : beans){
            fileIds.add(b.getId());
        }
        commit(fileIds);
    }

    @Override
    public void voidView(String message) {
        LoadDialog.dismiss(HelpAddActivity.this);
        ToastUtils.showToast(HelpAddActivity.this,message);
        MyRxBus.get().post(new MsgEvent("HelpActivity",1,null));
        finish();
    }
}
